/*
 * @(#)VistaDateUtil.java
 * Date 2012-12-30
 * Version 1.0
 * Author Jim Horner
 * Copyright (c)2012
 */


package com.chrisuyehara.vista.rpc.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;

import org.apache.commons.lang3.math.NumberUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 *
 * @author jim
 */
public class VistaDateUtil {

    /** Field description */
    private static final Logger logger =
        LoggerFactory.getLogger(VistaDateUtil.class);

    /**
     * Method description
     *
     *
     * @param dateToConvert
     *
     * @return
     */
    public static String createVistaDate(Date dateToConvert) {

        String result = null;

        if (dateToConvert != null) {

            Calendar cal = Calendar.getInstance();

            cal.setTime(dateToConvert);

            int year = cal.get(Calendar.YEAR) - 1700;

            SimpleDateFormat df = null;

            if ((cal.get(Calendar.HOUR_OF_DAY) == 0)
                    && (cal.get(Calendar.MINUTE) == 0)) {

                // drop time
                df = new SimpleDateFormat("MMdd");

            } else {

                df = new SimpleDateFormat("MMdd.HHmm");
            }

            // 3100525.1755 == yyymmdd.hhmm
            result = String.format("%d%s", year, df.format(dateToConvert));
        }

        return result;
    }

    /**
     * Method description
     *
     *
     *
     * @param datestr
     *
     * @return
     */
    public static Date parseVistaDate(String datestr) {

        Date result = null;

        if (StringUtils.isNotBlank(datestr)) {

            String ystr = StringUtils.substring(datestr, 0, 3);

            int year = NumberUtils.toInt(ystr, -1);

            if (year > 0) {

                year = year + 1700;

                DateFormat df = null;
                String noyear = StringUtils.substring(datestr, 3);
                String tstr = "";

                if (StringUtils.contains(noyear, ".")) {

                    df = new SimpleDateFormat("yyyyMMdd.HHmm");
                    tstr = StringUtils.rightPad(noyear, 9, "0");

                } else {

                    df = new SimpleDateFormat("yyyyMMdd");
                    tstr = noyear;
                }

                String finstr = String.format("%d%s", year, tstr);

                try {

                    result = df.parse(finstr);

                } catch (ParseException e) {

                    logger.warn("Unable to parse date.", e);
                }
            }
        }

        return result;
    }
}
